package com.zzz.demo.monitor.springjmx;

import com.zzz.demo.monitor.info.SystemInfo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

/**
 * 将监控的数据暴露给spring管理
 */
@Component
public class SomethingMXBeanRegistrar implements
        ApplicationContextAware,
        GenericApplicationListener,
        EnvironmentAware,
        InitializingBean,
        DisposableBean {

    private ConfigurableApplicationContext applicationContext;

    private Environment environment = new StandardEnvironment();

    private final ObjectName objectName = new ObjectName("com.zzz.demo.monitor.springjmx:type=SystemInfo");

    private boolean ready = false;

    private boolean embeddedWebApplication = false;

    public SomethingMXBeanRegistrar() throws MalformedObjectNameException {
    }

    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        SystemInfo info = new SystemInfo();
        server.registerMBean(info, objectName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return false;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

    }
}
